import {nuxtBaseUrl,WX_CONFIG,COOKIE_DOMAIN} from '../../config/index'
import {saveToLocal,loadFromLocal} from '../common/util/storage'
import Cookies from 'js-cookie'

export function getUserFromLocalStorage(sellerId) {
  console.log('进入getUserFromLocalStorage')
  console.log("sellerId:")
  console.log(sellerId)

  const userKey = WX_CONFIG.userLocalStorageName
  let userStr = loadFromLocal(sellerId,userKey,'')

  try{
    let user = JSON.parse(userStr)
    console.log('user:')
    console.log(user)
    return user
  }
  catch(err) {
    return null
  }

}

export function setUserToLocalStorage(sellerId, user) {
  console.log('进入setUserToLocalStorage')
  console.log("sellerId:")
  console.log(sellerId)

  const userKey = WX_CONFIG.userLocalStorageName
  saveToLocal(sellerId, userKey, user)

  console.log('user:')
  console.log(user)
}

export function clearUserToLocalStorage(sellerId) {
  console.log('进入clearUserFromLocalStorage')
  console.log("sellerId:")
  console.log(sellerId)

  const userKey = WX_CONFIG.userLocalStorageName
  let user = saveToLocal(sellerId,userKey,null)
}

// 删不掉user cookie，原因：
// 当前域名为www.monkeywood.club
export function clearUserToCookie(sellerId) {
  console.log('进入clearUserFromCookie')
  console.log("sellerId:")
  console.log(sellerId)

  const userKey = WX_CONFIG.userCookieName
  const userDomain = COOKIE_DOMAIN
  // 注意：前方巨坑
  // 此方法无效，不能删除cookie中的user
  // Cookies.remove(userKey);
  // 原因：
  // // 前端域名与cookie中的域名不一致
  // nuxt前端域名为:www.monkeywood.club
  // cookie中的域名为:monkeywood.club
  // spring boot后端的域名：api.monkeywood.club
  // 为了让nuxt前端能够获得spring boot后端传过来的cookie，cookie的域名设为二者共享的域名monkeywood.club
  // 此方法默认删除前端域名下的cookie，也就是www.monkeywood.club，但www.monkeywood.club下没有cookie，所以删除无效
  // 因此：前后端域名不同时，必须指定删除域名
  Cookies.remove(userKey, { domain:userDomain ,expires: 0, path: '/' });

}

// 向微信官服请求微信用户信息
// returnUrl：回调地址
export function requestUserInfoToWX(sellerId,returnUrl) {
  console.log('进入requestUserInfoToWX')
  
  console.log("sellerId:")
  console.log(sellerId)
  console.log("returnUrl:")
  console.log(returnUrl)

  const userKey = WX_CONFIG.userLocalStorageName
  
  returnUrl = encodeURIComponent(returnUrl)
  const subUrl = WX_CONFIG.getUserInfoStepOneUrl
  console.log(`${nuxtBaseUrl}${subUrl}?returnurl=${returnUrl}`)
  window.location.href = `${nuxtBaseUrl}${subUrl}?returnurl=${returnUrl}`

}

export function getUserFromCookie(sellerId) {
  console.log('进入requestUserInfoToWX')
  
  console.log("sellerId:")
  console.log(sellerId)
  
  const userKey = WX_CONFIG.userCookieName
  let userStr = Cookies.get(userKey)
  let userDecodedStr = decodeURIComponent(userStr)
  console.log(`get user in cookie ${userDecodedStr}:`)
  console.log(userDecodedStr)
  try{
    let user = JSON.parse(userDecodedStr)
    return user
  }catch(err){
    return null
  }
  
}